import java.util.ArrayList;

/**
 * Created by L.jp
 * Description:
 * User: 86189
 * Date: 2022-10-10
 * Time: 23:54
 */
public class Solution {
    public ArrayList<Integer> spiralOrder(int[][] matrix) {
        ArrayList<Integer> res = new ArrayList<>();
        if(matrix.length == 0) { //先排除特殊情况
            return res;
        }
        int left = 0; //左边界
        int right = matrix[0].length - 1; //右边界
        int up = 0; //上边界
        int down = matrix.length - 1; //下边界
    
        while(left <= right && up <= down){ //直到边界重合
            for(int i = left; i <= right; i++) //上边界的从左到右
                res.add(matrix[up][i]);
            up++; //上边界向下
            if(up > down)
                break;
            for(int i = up; i <= down; i++) //右边界的从上到下
                res.add(matrix[i][right]);
            right--; //右边界向左
            if(left > right)
                break;
            for(int i = right; i >= left; i--) //下边界的从右到左
                res.add(matrix[down][i]);
            down--; //下边界向上
            if(up > down)
                break;
            for(int i = down; i >= up; i--) //左边界的从下到上
                res.add(matrix[i][left]);
            left++; //左边界向右
            if(left > right)
                break;
        }
        return res;
    }
}
